/**
 *
 */
package com.guo.hui.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;

import org.bson.Document;

import com.alibaba.fastjson.JSONObject;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;

/**
 * @author zhengguohui
 * @className FileFataToMongodb
 * @description
 * @date 2018年7月23日
 */
public class FileFataToMongodb {

    public static void main(String[] args) {
        String path = "D:/ceshiwenjian";
        String content = "";
        File file1 = new File(path);
        MongoCollection<Document> mongo = mongodb("47.104.139.62:27017", "demo", "FileToMongo");
//        if (file1.exists()) {
//            File[] files = file1.listFiles();
//
//            for (File file : files) {
//                content = readFile(file);
////                String obj = JSONObject.toJSONString(content);
//                Document doc = Document.parse("");
//                mongo.insertOne(doc);
//            }
//        } else {
//            System.out.println("文件不存在!");
//        }
    }

    public static String readFile(File file) {
        StringBuilder localStrBulider = new StringBuilder();
        if (file.isFile() && file.exists()) {
            try {
                // InputStreamReader inputStreamReader = new
                // InputStreamReader(new FileInputStream(file), "gbk");
                InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(file), "gb2312");
                BufferedReader bufferReader = new BufferedReader(inputStreamReader);
                String lineStr = null;
                try {
                    while ((lineStr = bufferReader.readLine()) != null) {
                        localStrBulider.append(lineStr);
                    }
                    bufferReader.close();
                    inputStreamReader.close();
                } catch (IOException e) {
                    bufferReader.close();
                    inputStreamReader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return localStrBulider.toString();

    }

    private static MongoCollection<Document> mongodb(String address, String dataname, String coll) {
        MongoClient mongoClient = new MongoClient(address);
        MongoDatabase db = mongoClient.getDatabase(dataname);
        MongoCollection<Document> mongo = db.getCollection(coll);
        return mongo;
    }

}
